﻿using BrnMall.Core;
using BrnMall.Manager.Domain.Store;
using BrnMall.Manager.Manager.PC;
using BrnMall.Manager.Manager.Store;
using BrnMall.Services;
using BrnMall.Web.Framework;
using BrnMall.Web.StoreAdmin.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace BrnMall.Web.StoreAdmin.controllers
{
    /// <summary>
    /// PC网站控制器
    /// </summary>
    public partial class PcController : BaseStoreAdminController
    {
        /// <summary>
        /// 预览
        /// </summary>
        /// <returns></returns>
        public ActionResult Preview()
        {
            //PC网站配置
            var model = PcConfigManager.GetByStoreId(WorkContext.StoreId);
            if (model == null)
                model = new Manager.Domain.PC.PcConfig();
            return View(model);
        }

        #region PC组件设置

        /// <summary>
        /// 组件列表
        /// </summary>
        /// <param name="code"></param>
        /// <param name="cid"></param>
        /// <returns></returns>
        public ActionResult WidgetConfigList(string code, int cid = 0)
        {
            if (string.IsNullOrEmpty(code))
                return PromptView("组件Code不能为空");
            var widget = WidgetManager.GetWidget(WorkContext.StoreId, code);
            var uploadTips = string.Empty;
            if (widget == null)
            {
                var newWidget = new Widget { Code = code, IsActive = true, StoreId = WorkContext.StoreId };
                if (code == "index_banner")
                    newWidget.Name = "首页轮播";
                else if (code == "index_nav_icon")
                {
                    newWidget.Name = "首页按钮导航";
                }
                else if (code == "index_product")
                    newWidget.Name = "首页商品";
                WidgetManager.InsertWidget(newWidget);
                widget = WidgetManager.GetWidget(WorkContext.StoreId, code);
            }

            if (widget.Code == "index_banner")
            {
                uploadTips = "正方形建议800x800,长方形建议800x500";
            }
            else if (widget.Code == "pc_index_banner")
            {
                uploadTips = "建议1920*500";
            }
            else if (widget.Code == "pc_index_product")
            {
                uploadTips = "建议325x325";
            }
            else if (widget.Code == "index_nav_icon")
            {
                uploadTips = "建议100x100";
            }
            else if (widget.Code == "pc_index_news")
            {
                uploadTips = "建议尺寸1000*210";
            }
            else if (widget.Code == "index_product")
                uploadTips = "建议500x70";
            var widgetModel = new WidgetModel
            {
                Code = widget.Code,
                Name = widget.Name,
                StoreId = widget.StoreId,
                WId = widget.WId
            };
            var config = WidgetManager.GetConfigList(widget.WId).Select(t => new WidgetConfigModel
            {
                CId = t.CId,
                IsShow = t.IsShow,
                LinkType = t.LinkType,
                LinkValue = JsonConvert.DeserializeObject<LinkValue>(t.LinkValue),
                ShowName = t.ShowName,
                ShowImg = t.ShowImg,
                DisplayOrder = t.DisplayOrder,
                WId = t.WId,
                DisplayCount = t.DisplayCount,
                DisplayType = t.DisplayType,
                DisplayPosition = t.DisplayPosition
            }).ToList();

            //单个组件实体
            WidgetConfig configModel = cid < 1 ? new WidgetConfig() : WidgetManager.GetConfig(cid);

            var model = new WidgetConfigListModel
            {
                Config = config,
                Widget = widgetModel,
                StoreClassList = Stores.GetStoreClassList(WorkContext.StoreId),
                NewsTypeList = News.GetStoreNewsTypeList(WorkContext.StoreId),
                Code = code,
                PageInfos = PageInfoConfig.Pages,
                FunctionCodes = FunctionCodeInfoConfig.FunctionCodes,
                UploadImageTips = uploadTips,
                configModel = configModel
            };
            MallUtils.SetAdminRefererCookie($"{Url.Action("WidgetConfigList")}?code={code}");
            Load();
            if (code == "index_product")
                return View("IndexProductWidgetConfigList", model);
            else if (code == "pc_index_news" || code == "pc_index_nav")
                return View("NewsWidgetConfigList", model); //内容组件(pc网站用到)

            return View(model);
        }

        /// <summary>
        /// 添加组件
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddWidgetConfig(WidgetConfigPostModel model)
        {
            var con = new WidgetConfig
            {
                CId = model.CId,
                IsShow = model.IsShow,
                LinkType = model.LinkType,
                DisplayCount = model.DisplayCount,
                DisplayType = model.DisplayType
            };
            if (string.IsNullOrEmpty(model.LinkType))
                return PromptView("请选择链接类型");
            var linkValue = new LinkValue();
            switch (con.LinkType)
            {
                case "product":
                    if (string.IsNullOrEmpty(model.Pid))
                        return PromptView("链接到商品时，没有指定商品");
                    linkValue.Id = model.Pid;
                    linkValue.Name = model.ProductName;
                    linkValue.LinkType = con.LinkType;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;

                case "store_class":
                    if (string.IsNullOrEmpty(model.StoreClassId))
                        return PromptView("链接到店铺分类时，没有指定店铺分类");
                    linkValue.LinkType = con.LinkType;
                    linkValue.Id = model.StoreClassId;
                    linkValue.Name = Stores.GetStoreClassByStoreIdAndStoreCid(WorkContext.StoreId, TypeHelper.StringToInt(model.StoreClassId)).Name;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;

                case "news":
                    if (string.IsNullOrEmpty(model.NewsId))
                        return PromptView("链接到内容时，没有指定内容");
                    linkValue.LinkType = con.LinkType;
                    linkValue.Id = model.NewsId;
                    linkValue.Name = model.NewsName;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;

                case "news_type":
                    if (string.IsNullOrEmpty(model.NewsTypeId))
                        return PromptView("链接到内容分类时，没有指定内容分类");
                    linkValue.LinkType = con.LinkType;
                    linkValue.Id = model.NewsTypeId;
                    linkValue.Name = News.GetStoreNewsTypeById(WorkContext.StoreId, TypeHelper.StringToInt(model.NewsTypeId)).Name;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;

                case "page":
                    if (string.IsNullOrEmpty(model.PageInfoId))
                        return PromptView("链接到页面时，没有指定页面");
                    var pageInfo = PageInfoConfig.Get(model.PageInfoId);
                    linkValue.Id = pageInfo.Id;
                    linkValue.Url = pageInfo.Url;
                    linkValue.Name = pageInfo.Name;
                    linkValue.LinkType = con.LinkType;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;

                case "productattr":
                    if (string.IsNullOrEmpty(model.ProductAttr))
                        return PromptView("链接到商品特征时，没有指定商品特征");
                    linkValue.Id = model.ProductAttr;
                    var name = string.Empty;
                    if (linkValue.Id == "hot")
                        name = "热销";
                    else if (linkValue.Id == "new")
                        name = "新品";
                    else if (linkValue.Id == "best")
                        name = "精品";
                    linkValue.Name = name;
                    linkValue.LinkType = con.LinkType;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;

                case "h5page":
                    if (string.IsNullOrEmpty(model.H5Page))
                        return PromptView("链接到H5网页时，没有指定网页路径");

                    Uri url;
                    var t = Uri.TryCreate(model.H5Page, UriKind.Absolute, out url);
                    if (!t)
                        return PromptView("网页路径格式错误");
                    //if (!url.Scheme.Equals("https"))
                    //    return PromptView("必须是https网页路径格式");
                    linkValue.Id = "0";
                    linkValue.Url = model.H5Page;
                    linkValue.Name = string.Empty;
                    linkValue.LinkType = con.LinkType;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;

                default:
                    linkValue.Id = string.Empty;
                    linkValue.Name = string.Empty;
                    linkValue.LinkType = string.Empty;
                    break;
            }

            con.ShowImg = model.ShowImg ?? "";
            con.ShowName = model.ShowName ?? "";
            con.DisplayOrder = model.DisplayOrder;
            con.WId = model.WId;

            if (con.CId > 0)
            {
                WidgetManager.UpdateConfig(con);    //修改
                return PromptView(Url.Action("WidgetConfigList", "PC", new { code = model.Code }), "修改成功");
            }
            else
            {
                var code = "pc_index_nav";
                var widget = WidgetManager.GetWidget(WorkContext.StoreId, code = code);
                var config = WidgetManager.GetConfigList(widget.WId).ToList();
                if (config.Count >= 5 & con.LinkType == "store_class")
                {
                    return PromptView("网站导航不能超过5个");
                }
                else
                {
                    WidgetManager.InsertConfig(con);    //添加
                    return PromptView(Url.Action("WidgetConfigList", "PC", new { code = model.Code }), "添加成功");
                }
            }
        }

        [HttpPost]
        public ActionResult AddIndexPictureWidgetConfig(IndexPictureWidgetConfigPostModel model, string code = "")
        {
            var con = new WidgetConfig
            {
                IsShow = model.IsShow,
                DisplayType = model.DisplayType,
                ShowName = model.ShowName,
                DisplayOrder = model.DisplayOrder,
                DisplayPosition = model.DisplayPosition,
                WId = model.WId
            };
            WidgetManager.InsertConfig(con);
            var wiget = WidgetManager.GetWidget(con.WId);

            return PromptView(Url.Action("IndexPictureWidgetConfigList", new { code = code }), "新增成功");
        }

        public ActionResult IndexPictureWidgetConfigList(string code = "")
        {
            code = code == "" ? "index_pic_area" : code;

            var widget = WidgetManager.GetWidget(WorkContext.StoreId, code);
            if (widget == null)
            {
                widget = new Widget
                {
                    Code = code,
                    IsActive = true,
                    StoreId = WorkContext.StoreId,
                    Name = "首页图片组件"
                };
                WidgetManager.InsertWidget(widget);
            }
            var widgetModel = new WidgetModel
            {
                Code = widget.Code,
                Name = widget.Name,
                StoreId = widget.StoreId,
                WId = widget.WId
            };
            var config = WidgetManager.GetConfigList(widget.WId).Select(t => new WidgetConfigModel
            {
                CId = t.CId,
                IsShow = t.IsShow,
                ShowName = t.ShowName,
                ShowImg = t.ShowImg,
                DisplayOrder = t.DisplayOrder,
                WId = t.WId,
                DisplayType = t.DisplayType,
                DisplayPosition = t.DisplayPosition
            }).ToList();

            var model = new WidgetConfigListModel
            {
                Config = config,
                Widget = widgetModel,
                Code = code
            };

            Load();
            return View(model);
        }

        #endregion PC组件设置

        private void Load()
        {
            ViewData["allowImgType"] = BMAConfig.UploadConfig.UploadImgType.Replace(".", "");
            ViewData["maxImgSize"] = BMAConfig.UploadConfig.UploadImgSize;
            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
        }

        public ActionResult ChangeWidgetConfigSort(int cid, int displayOrder = 0)
        {
            WidgetManager.SortConfig(cid, displayOrder);
            return Content("1");
        }

        public ActionResult DeleteIndexPictureCustomerFeatures(int cid, int itemIndex)
        {
            if (cid < 1) return Content("0");
            var t = WidgetManager.GetConfig(cid);
            var pics = JsonConvert.DeserializeObject<IList<LinkValue>>(t.CustomerFeatures);
            var find = pics.SingleOrDefault(x => x == pics[itemIndex]);
            if (find != null)
                pics = pics.Where(x => x != pics[itemIndex]).ToList();
            t.CustomerFeatures = JsonConvert.SerializeObject(pics);
            WidgetManager.UpdateWidgetCustomerFeatures(cid, t.CustomerFeatures);
            return Content("1");
        }

        public ActionResult EditIndexPictureCustomerFeatures(int cid, string Code)
        {
            if (cid < 1) return PromptView("参数错误");
            var t = WidgetManager.GetConfig(cid);
            var model = new EditIndexPictureWidgetCustomerFeaturesModel
            {
                WidgetConfig = new WidgetConfigModel
                {
                    CId = t.CId,
                    IsShow = t.IsShow,
                    ShowName = t.ShowName,
                    DisplayOrder = t.DisplayOrder,
                    WId = t.WId,
                    DisplayType = t.DisplayType,
                    DisplayPosition = t.DisplayPosition
                },

                StoreClassList = Stores.GetStoreClassList(WorkContext.StoreId),
                NewsTypeList = News.GetStoreNewsTypeList(WorkContext.StoreId),
                PageInfos = PageInfoConfig.Pages,
                FunctionCodes = FunctionCodeInfoConfig.FunctionCodes,
            };
            if (!string.IsNullOrEmpty(t.CustomerFeatures))
                model.CustomerFeatures = JsonConvert.DeserializeObject<IList<LinkValue>>(t.CustomerFeatures);
            if (t.DisplayType > 10 && t.DisplayType < 20)
                model.LinkArea = new[] { "A", "B", "C", "D", "E", "F" }.Take(t.DisplayType - 10).ToArray();
            if (t.DisplayType == 11)
            {
                model.UploadTips.Add("建议尺寸:980*300");
            }
            else if (t.DisplayType == 12)
            {
                model.UploadTips.Add("长款比例1:1，建议最低像素480*290");
            }
            else if (t.DisplayType == 14)
            {
                model.UploadTips.Add("长款比例1:1，建议最低像素480*140");
            }
            else if (t.DisplayType == 13)
            {
                model.UploadTips.Add("图片区域A：长款比例1:1，建议最低像素480*290");
                model.UploadTips.Add("图片区域B,C：长款比例2:1，建议最低像素480*140");
            }
            else if (t.DisplayType == 15)
            {
                model.UploadTips.Add("图片区域A：长款比例1:2，建议最低像素320*295");
                model.UploadTips.Add("图片区域B,C,D,E：长款比例1:1，建议最低像素315*140");
            }
            MallUtils.SetAdminRefererCookie(Url.Action("IndexPictureWidgetConfigList", "pc", new { code = Code }));
            Load();
            return View(model);
        }

        public ActionResult DeleteWidgetConfig(int cid)
        {
            WidgetManager.DeleteConfig(cid);
            return Content("1");
        }

        [HttpPost]
        public ActionResult AddIndexPictureCustomerFeatures(EditIndexPictureWidgetCustomerFeaturesPostModel model)
        {
            if (model.CId < 1) return PromptView("参数错误");
            MallUtils.SetAdminRefererCookie(Url.Action("EditIndexPictureCustomerFeatures", "pc", new { cid = model.CId }));
            var t = WidgetManager.GetConfig(model.CId);
            var pics = JsonConvert.DeserializeObject<IList<LinkValue>>(t.CustomerFeatures) ?? new List<LinkValue>();
            var find = pics.SingleOrDefault(x => x.LinkArea == model.LinkArea);
            if (find != null)
                return PromptView($"区域{model.LinkArea}已经定义了图片");
            var linkValue = new LinkValue
            {
                LinkType = model.LinkType,
                LinkArea = model.LinkArea,
                ShowImg = model.ShowImg
            };
            switch (linkValue.LinkType)
            {
                case "product":
                    if (string.IsNullOrEmpty(model.Pid))
                        return PromptView("请选择商品");
                    linkValue.Id = model.Pid;
                    linkValue.Name = model.ProductName;
                    break;

                case "store_class":
                    if (string.IsNullOrEmpty(model.StoreClassId))
                        return PromptView("请选择店铺分类");
                    linkValue.Id = model.StoreClassId;
                    linkValue.Name = Stores.GetStoreClassByStoreIdAndStoreCid(WorkContext.StoreId, TypeHelper.StringToInt(model.StoreClassId)).Name;
                    break;

                case "news":
                    if (string.IsNullOrEmpty(model.NewsId))
                        return PromptView("请选择内容");
                    linkValue.Id = model.NewsId;
                    linkValue.Name = model.NewsName;
                    break;

                case "news_type":
                    if (string.IsNullOrEmpty(model.NewsTypeId))
                        return PromptView("请选择内容分类");
                    linkValue.Id = model.NewsTypeId;
                    linkValue.Name = News.GetStoreNewsTypeById(WorkContext.StoreId, TypeHelper.StringToInt(model.NewsTypeId)).Name;
                    break;

                case "page":
                    if (string.IsNullOrEmpty(model.PageInfoId))
                        return PromptView("请选择页面");
                    var pageInfo = PageInfoConfig.Get(model.PageInfoId);
                    linkValue.Id = pageInfo.Id;
                    linkValue.Url = pageInfo.Url;
                    linkValue.Name = pageInfo.Name;
                    break;

                case "h5page":
                    if (string.IsNullOrEmpty(model.H5Page))
                        return PromptView("链接到H5网页时，没有指定网页路径");

                    Uri url;
                    var h5 = Uri.TryCreate(model.H5Page, UriKind.Absolute, out url);
                    if (!h5)
                        return PromptView("网页路径格式错误");
                    if (!url.Scheme.Equals("https"))
                        return PromptView("必须是https网页路径格式");
                    linkValue.Id = "0";
                    linkValue.Url = model.H5Page;
                    linkValue.Name = string.Empty;
                    break;

                case "phonecall":
                    if (string.IsNullOrEmpty(model.PhoneNumber))
                        return PromptView("链接到一键拨号时，没有指定号码");
                    linkValue.Id = "0";
                    linkValue.Url = "";
                    linkValue.Name = model.PhoneNumber;

                    break;

                case "weappfunc":
                    if (string.IsNullOrEmpty(model.FunctionCode))
                        return PromptView("链接到扫码时，没有指定二维码");
                    linkValue.Id = "0";
                    linkValue.Url = "";
                    linkValue.Name = model.FunctionCode;
                    break;

                default:
                    linkValue.Id = string.Empty;
                    linkValue.Name = string.Empty;
                    linkValue.LinkType = string.Empty;
                    break;
            }
            if (string.IsNullOrEmpty(linkValue.Id))
                return PromptView("选择链接错误");
            pics.Add(linkValue);
            var features = JsonConvert.SerializeObject(pics);
            WidgetManager.UpdateWidgetCustomerFeatures(model.CId, features);

            return PromptView("新增成功");
        }
    }
}